<template>
  <div class="login-container">
    <div class="login-box">
      <div class="title">仓库管理系统</div>
      <a-form ref="loginFormRef" :model="form" layout="vertical" @submit="handleLogin">
        <a-form-item
          field="username"
          label="用户名"
          :rules="[{ required: true, message: '请输入用户名' }]"
          :validate-trigger="['blur']"
        >
          <a-input v-model="form.username" placeholder="请输入用户名..."/>
        </a-form-item>
        <a-form-item
          field="password"
          label="密码"
          :rules="[{ required: true, message: '请输入密码' }]"
          :validate-trigger="['blur']"
        >
          <a-input-password v-model="form.password" placeholder="请输入密码..."/>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" long :loading="loading">
            登 录
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {Message} from '@arco-design/web-vue'
import {useUserStore} from '@/stores/user'
import {loginApi} from '@/api/auth'
import type {LoginRequest} from '@/types/api/auth'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const form = reactive<LoginRequest>({
  username: '',
  password: ''
})

const loginFormRef = ref(null)

const handleLogin = async ({values, errors}: { values: any; errors: any }) => {
  if (errors) {
    return
  }
  loading.value = true
  try {
    const res = await loginApi(values)
    // 假设后端返回的数据结构是 { success: true, data: { token: 'xxx' } }
    userStore.setToken(res.token)
    await userStore.fetchUserInfo()
    Message.success('登录成功！')
    router.push('/') // 登录成功后跳转到首页
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: var(--color-bg-1);
}

.login-box {
  width: 360px;
  padding: 40px;
  background-color: var(--color-bg-2);
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 24px;
  color: var(--color-text-1);
}
</style>
